﻿using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using AutoMapper;
using PagedList;
using SIG.Service;
using SIG.Model;
using System;

using SIG.WebMVC.Filters;
using SIG.Infrastructure.Configs;
using SIG.Model.Enums;
using SIG.ViewModel;
using SIG.Infrastructure.Extensions;
using System.Xml.Linq;
using SIG.Infrastructure.Helper;
using SIG.Resources.Admin;
using SIG.Service.Case;
using SIG.ViewModel.Admin.Case;
using SIG.Model.Case;
using SIG.InputModel.Admin.Case;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class WorkController : BaseController
    {
        private readonly IWorkTypeService _workTypeService;
        private readonly IWorkService _workService;
        private readonly ISolutionService _solutionService;
        private readonly IClientService _clientService;
        private readonly IPageMetaService _pageMetaService;
        private readonly IMapper _mapper;

        public WorkController(IWorkTypeService workTypeService, IWorkService workService, 
            ISolutionService solutionService, IClientService clientService, IPageMetaService pageMetaService, IMapper mapper)
        {
            _workTypeService = workTypeService;
            _workService = workService;
            _solutionService = solutionService;
            _clientService = clientService;
            _pageMetaService = pageMetaService;
            _mapper = mapper;
        }
        #region Works


        [HttpGet]
        public ActionResult Index(int? page, int? typeId, string Keyword)
        {

            var workListVM = new WorkListVM();

            workListVM.CategoryId = typeId ?? 0;
            workListVM.PageIndex = (page ?? 1) - 1;
            workListVM.PageSize = SettingsManager.Case.PageSize;
            workListVM.Keyword = Keyword;

            int count;
            var works = _workService.GetPagedElements(workListVM.PageIndex, workListVM.PageSize, workListVM.Keyword, workListVM.CategoryId, out count);

            var workDtos = _mapper.Map<IEnumerable<Work>, IEnumerable<WorkVM>>(works.AsEnumerable());

            //   workListVM.Works = workDtos;
            workListVM.TotalCount = count;

            var workTypeList = _workTypeService.GetAll().OrderByDescending(c => c.Importance).ToList();
            var categories = new SelectList(workTypeList, "Id", "Title");
            ViewBag.Categories = categories;

            workListVM.Works = new StaticPagedList<WorkVM>(workDtos, workListVM.PageIndex + 1, workListVM.PageSize, workListVM.TotalCount);
            //  ViewBag.OnePageOfWorks = worksAsIPagedList;

            ViewBag.PageSizes = new SelectList(Site.PageSizes());

            return View(workListVM);

        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/CaseSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        public ActionResult Add()
        {
            var work = new WorkIM { Active = true };


            var solutions = _solutionService.FindBy(m=>m.Active).OrderByDescending(c => c.Importance).ToList();
            var lSolutions = new SelectList(solutions, "Id", "Title");
            ViewBag.Solutions = lSolutions;


            var clients = _clientService.FindBy(m => m.Active).OrderByDescending(c => c.Importance).ToList();
            var lClients = new SelectList(clients, "Id", "ClientName");
            ViewBag.Clients = lClients;


            ViewBag.Types = _workTypeService.FindBy(m => m.Active).OrderByDescending(t => t.Importance).ToList();

            return View(work);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Add(WorkIM work)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {

                var newWork = _mapper.Map<WorkIM, Work>(work);

                if (work.WorkTypesIds != null)
                {
                    var lCategories = (from c in _workTypeService.GetAll()
                                       where work.WorkTypesIds.Contains(c.Id.ToString())
                                       select c).ToList();

                    newWork.WorkTypes = lCategories;
                    newWork.TypeIds = string.Join(",", work.WorkTypesIds);
                }

                _workService.Create(newWork);

                if (!string.IsNullOrEmpty(work.Keywords) || !string.IsNullOrEmpty(work.SEODescription))
                {
                    var pageMeta = new PageMeta()
                    {
                        ObjectId = newWork.Id,
                        Keyword = work.Keywords.Replace("，", ","),
                        Description = work.SEODescription,
                        ModelType = ModelType.WORK
                    };
                    _pageMetaService.Create(pageMeta);
                }

                AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }

        [HttpGet]
        public ActionResult Edit(int Id)
        {
            var vWork = _workService.GetById(Id);
            if (vWork == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }


            var editWork = _mapper.Map<Work, WorkIM>(vWork);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.WORK, editWork.Id);
            if (pageMeta != null)
            {
                editWork.Keywords = pageMeta.Keyword;
                editWork.SEODescription = pageMeta.Description;
            }


            var solutions = _solutionService.FindBy(m => m.Active).OrderByDescending(c => c.Importance).ToList();
            var lSolutions = new SelectList(solutions, "Id", "Title");
            ViewBag.Solutions = lSolutions;


            var clients = _clientService.FindBy(m => m.Active).OrderByDescending(c => c.Importance).ToList();
            var lClients = new SelectList(clients, "Id", "ClientName");
            ViewBag.Clients = lClients;


            ViewBag.Types = _workTypeService.FindBy(m => m.Active).OrderByDescending(t => t.Importance).ToList();

            return View(editWork);


        }

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public JsonResult Edit(WorkIM workIM)
        {
            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                // var editWork = _mapper.Map<WorkIM, Work>(work);
                var existingWork = _workService.GetById(workIM.Id);

                existingWork.SolutionId = workIM.SolutionId;
                existingWork.FinishYear = workIM.FinishYear;
                existingWork.Title = workIM.Title;
                existingWork.ClientId = workIM.ClientId;
                existingWork.Demourl = workIM.Demourl;
                existingWork.Abstract = workIM.Abstract;
                existingWork.Body = workIM.Body;
                existingWork.ImageUrl = workIM.ImageUrl;              
                existingWork.Thumbnail = workIM.Thumbnail;
                existingWork.Active = workIM.Active;
                existingWork.Recommend = workIM.Recommend;


                existingWork.WorkTypes.Clear();

                if (workIM.WorkTypesIds != null)
                {
                    existingWork.TypeIds = string.Join(",", workIM.WorkTypesIds);
                    var lCategories = (from c in _workTypeService.GetAll()
                                       where workIM.WorkTypesIds.Contains(c.Id.ToString())
                                       select c).ToList();
                    existingWork.WorkTypes = lCategories;  //分类付值
                }
                else
                {
                    existingWork.TypeIds = string.Empty;
                }


                _workService.Update(existingWork);

                var pageMeta = _pageMetaService.GetPageMeta(ModelType.WORK, existingWork.Id);
                pageMeta = pageMeta ?? new PageMeta();


                if (!string.IsNullOrEmpty(workIM.Keywords) || !string.IsNullOrEmpty(workIM.SEODescription))
                {

                    pageMeta.ObjectId = workIM.Id;
                    pageMeta.Keyword = workIM.Keywords;
                    pageMeta.Description = workIM.SEODescription;
                    pageMeta.ModelType = ModelType.WORK;

                    if (pageMeta.Id > 0)
                    {
                        _pageMetaService.Update(pageMeta);
                    }
                    else
                    {
                        _pageMetaService.Create(pageMeta);
                    }
                }

                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception er)
            {
                AR.Setfailure(er.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }


        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Active(int id)
        {

            Work vWork = _workService.GetById(id);

            try
            {
                vWork.Active = !vWork.Active;
                _workService.Update(vWork);

                var vm = _mapper.Map<WorkVM>(vWork);

                AR.Data = RenderPartialViewToString("_WorkItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Recommend(int id)
        {

            Work vWork = _workService.GetById(id);

            try
            {
                vWork.Recommend = !vWork.Recommend;
                _workService.Update(vWork);

                var vm = _mapper.Map<WorkVM>(vWork);
                AR.Data = RenderPartialViewToString("_WorkItem", vm);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Work));
                return Json(AR, JsonRequestBehavior.DenyGet);

            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Work vWork = _workService.GetById(id);
            if (vWork == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            vWork.WorkTypes.Clear();
            _workService.Delete(vWork);

            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Work));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        #endregion


    }
}
